
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_Hans">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>加密签名 &#8212; Django 3.2.11.dev 文档</title>
    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/language_data.js"></script>
    <link rel="index" title="索引" href="../genindex.html" />
    <link rel="search" title="搜索" href="../search.html" />
    <link rel="next" title="发送邮件" href="email.html" />
    <link rel="prev" title="条件视图处理" href="conditional-view-processing.html" />



 
<script src="../templatebuiltins.js"></script>
<script>
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../ref/templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);</script>

  </head><body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../index.html">Django 3.2.11.dev 文档</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../index.html">Home</a>  |
        <a title="Table of contents" href="../contents.html">Table of contents</a>  |
        <a title="Global index" href="../genindex.html">Index</a>  |
        <a title="Module index" href="../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="conditional-view-processing.html" title="条件视图处理">previous</a>
     |
    <a href="index.html" title="使用 Django" accesskey="U">up</a>
   |
    <a href="email.html" title="发送邮件">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="topics-signing">
            
  <div class="section" id="s-module-django.core.signing">
<span id="s-cryptographic-signing"></span><span id="module-django.core.signing"></span><span id="cryptographic-signing"></span><h1>加密签名<a class="headerlink" href="#module-django.core.signing" title="永久链接至标题">¶</a></h1>
<p>Web 应用程序安全的黄金法则是永远不要信任来自不受信任来源的数据。有时，通过不受信任的媒介传递数据是有用的。经过加密签名的值可以通过不受信任的渠道传递，因为知道任何篡改都会被检测到。</p>
<p>Django 提供了用于签署值的低级 API 和用于设置和读取已签名 cookie 的高级 API，这是 Web 应用程序中签名的最常见用法之一。</p>
<p>你可能还发现签名对以下方面很有用：</p>
<ul class="simple">
<li>生成“找回我的账户”URL 以发送给丢失密码的用户。</li>
<li>确认存储在表单隐藏字段中的数据未被篡改。</li>
<li>生成一次性的秘密 URL，允许临时访问受保护的资源，例如用户付费下载的文件。</li>
</ul>
<div class="section" id="s-protecting-the-secret-key">
<span id="protecting-the-secret-key"></span><h2>保护 <code class="docutils literal notranslate"><span class="pre">SECRET_KEY</span></code><a class="headerlink" href="#protecting-the-secret-key" title="永久链接至标题">¶</a></h2>
<p>当你使用 <a class="reference internal" href="../ref/django-admin.html#django-admin-startproject"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">startproject</span></code></a> 创建一个新的Django项目时，<code class="docutils literal notranslate"><span class="pre">settings.py</span></code> 文件会自动生成，并随机得到一个 <a class="reference internal" href="../ref/settings.html#std:setting-SECRET_KEY"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECRET_KEY</span></code></a> 值。这个值是保证签名数据安全的关键——你必须保证这个值的安全，否则攻击者可以用它来生成自己的签名值。</p>
</div>
<div class="section" id="s-using-the-low-level-api">
<span id="using-the-low-level-api"></span><h2>使用低级 API<a class="headerlink" href="#using-the-low-level-api" title="永久链接至标题">¶</a></h2>
<p>Django 的签名方法位于 <code class="docutils literal notranslate"><span class="pre">django.core.signing</span></code> 模块中。要签署一个值，首先要实例化一个 <code class="docutils literal notranslate"><span class="pre">Signer</span></code> 实例：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.core.signing</span> <span class="kn">import</span> <span class="n">Signer</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">signer</span> <span class="o">=</span> <span class="n">Signer</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">value</span> <span class="o">=</span> <span class="n">signer</span><span class="o">.</span><span class="n">sign</span><span class="p">(</span><span class="s1">&#39;My string&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">value</span>
<span class="go">&#39;My string:GdMGD6HNQ_qdgxYP8yBZAdAIV1w&#39;</span>
</pre></div>
</div>
<p>签名被附加在字符串的结尾，在冒号之后。你可以使用 <code class="docutils literal notranslate"><span class="pre">unsign</span></code> 方法检索原始值：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">original</span> <span class="o">=</span> <span class="n">signer</span><span class="o">.</span><span class="n">unsign</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">original</span>
<span class="go">&#39;My string&#39;</span>
</pre></div>
</div>
<p>如果你将非字符串值传递给 <code class="docutils literal notranslate"><span class="pre">sign</span></code>，该值将在被签署前被强制变成字符串，并且 <code class="docutils literal notranslate"><span class="pre">unsign</span></code> 结果将返回此字符串值：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">signed</span> <span class="o">=</span> <span class="n">signer</span><span class="o">.</span><span class="n">sign</span><span class="p">(</span><span class="mf">2.5</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">original</span> <span class="o">=</span> <span class="n">signer</span><span class="o">.</span><span class="n">unsign</span><span class="p">(</span><span class="n">signed</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">original</span>
<span class="go">&#39;2.5&#39;</span>
</pre></div>
</div>
<p>If you wish to protect a list, tuple, or dictionary you can do so using the
<code class="docutils literal notranslate"><span class="pre">sign_object()</span></code> and <code class="docutils literal notranslate"><span class="pre">unsign_object()</span></code> methods:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">signed_obj</span> <span class="o">=</span> <span class="n">signer</span><span class="o">.</span><span class="n">sign_object</span><span class="p">({</span><span class="s1">&#39;message&#39;</span><span class="p">:</span> <span class="s1">&#39;Hello!&#39;</span><span class="p">})</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">signed_obj</span>
<span class="go">&#39;eyJtZXNzYWdlIjoiSGVsbG8hIn0:Xdc-mOFDjs22KsQAqfVfi8PQSPdo3ckWJxPWwQOFhR4&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">obj</span> <span class="o">=</span> <span class="n">signer</span><span class="o">.</span><span class="n">unsign_object</span><span class="p">(</span><span class="n">signed_obj</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">obj</span>
<span class="go">{&#39;message&#39;: &#39;Hello!&#39;}</span>
</pre></div>
</div>
<p>See <a class="reference internal" href="#signing-complex-data"><span class="std std-ref">保护复杂的数据结构</span></a> for more details.</p>
<p>如果签名或值被以任何方式修改，将引发 <code class="docutils literal notranslate"><span class="pre">django.core.signing.BadSignature</span></code> 异常：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.core</span> <span class="kn">import</span> <span class="n">signing</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">value</span> <span class="o">+=</span> <span class="s1">&#39;m&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">try</span><span class="p">:</span>
<span class="gp">... </span>   <span class="n">original</span> <span class="o">=</span> <span class="n">signer</span><span class="o">.</span><span class="n">unsign</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>
<span class="gp">... </span><span class="k">except</span> <span class="n">signing</span><span class="o">.</span><span class="n">BadSignature</span><span class="p">:</span>
<span class="gp">... </span>   <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Tampering detected!&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>默认情况下，<code class="docutils literal notranslate"><span class="pre">Signer</span></code> 类使用 <a class="reference internal" href="../ref/settings.html#std:setting-SECRET_KEY"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECRET_KEY</span></code></a> 配置来生成签名。你可以使用不同的密钥传入 <code class="docutils literal notranslate"><span class="pre">Signer</span></code> 构造函数生成不同的签名：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">signer</span> <span class="o">=</span> <span class="n">Signer</span><span class="p">(</span><span class="s1">&#39;my-other-secret&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">value</span> <span class="o">=</span> <span class="n">signer</span><span class="o">.</span><span class="n">sign</span><span class="p">(</span><span class="s1">&#39;My string&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">value</span>
<span class="go">&#39;My string:EkfQJafvGyiofrdGnuthdxImIJw&#39;</span>
</pre></div>
</div>
<dl class="class">
<dt id="django.core.signing.Signer">
<em class="property">class </em><code class="descname">Signer</code>(<em>key=None</em>, <em>sep=':'</em>, <em>salt=None</em>, <em>algorithm=None</em>)<a class="headerlink" href="#django.core.signing.Signer" title="永久链接至目标">¶</a></dt>
<dd><p>返回一个使用 <code class="docutils literal notranslate"><span class="pre">key</span></code> 生成签名并使用 <code class="docutils literal notranslate"><span class="pre">sep</span></code> 分隔值的签名器。<code class="docutils literal notranslate"><span class="pre">sep</span></code> 不能在 <span class="target" id="index-2"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc4648.html#section-5"><strong>URL 安全 base64 字母表</strong></a> 中。这个字母表包含字母数字字符、连字符和下划线。<code class="docutils literal notranslate"><span class="pre">algorithm</span></code> 必须是 <a class="reference external" href="https://docs.python.org/3/library/hashlib.html#module-hashlib" title="(在 Python v3.10)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">hashlib</span></code></a> 支持的算法。默认为 <code class="docutils literal notranslate"><span class="pre">'sha256'</span></code>。</p>
<div class="versionchanged">
<span class="title">Changed in Django 3.1:</span> <p>加入 <code class="docutils literal notranslate"><span class="pre">algorithm</span></code> 参数。</p>
</div>
</dd></dl>

<div class="versionchanged">
<span class="title">Changed in Django 3.2:</span> <p>The <code class="docutils literal notranslate"><span class="pre">sign_object()</span></code> and <code class="docutils literal notranslate"><span class="pre">unsign_object()</span></code> methods were added.</p>
</div>
<div class="section" id="s-using-the-salt-argument">
<span id="using-the-salt-argument"></span><h3>使用 <code class="docutils literal notranslate"><span class="pre">salt</span></code> 参数<a class="headerlink" href="#using-the-salt-argument" title="永久链接至标题">¶</a></h3>
<p>如果你不希望一个特定字符串的每一次出现都有相同的签名哈希值，你可以使用 <code class="docutils literal notranslate"><span class="pre">Signer</span></code> 类的可选 <code class="docutils literal notranslate"><span class="pre">salt</span></code> 参数。使用盐会将盐和你的 <a class="reference internal" href="../ref/settings.html#std:setting-SECRET_KEY"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECRET_KEY</span></code></a> 作为签名哈希函数的种子。</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">signer</span> <span class="o">=</span> <span class="n">Signer</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">signer</span><span class="o">.</span><span class="n">sign</span><span class="p">(</span><span class="s1">&#39;My string&#39;</span><span class="p">)</span>
<span class="go">&#39;My string:GdMGD6HNQ_qdgxYP8yBZAdAIV1w&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">signer</span><span class="o">.</span><span class="n">sign_object</span><span class="p">({</span><span class="s1">&#39;message&#39;</span><span class="p">:</span> <span class="s1">&#39;Hello!&#39;</span><span class="p">})</span>
<span class="go">&#39;eyJtZXNzYWdlIjoiSGVsbG8hIn0:Xdc-mOFDjs22KsQAqfVfi8PQSPdo3ckWJxPWwQOFhR4&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">signer</span> <span class="o">=</span> <span class="n">Signer</span><span class="p">(</span><span class="n">salt</span><span class="o">=</span><span class="s1">&#39;extra&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">signer</span><span class="o">.</span><span class="n">sign</span><span class="p">(</span><span class="s1">&#39;My string&#39;</span><span class="p">)</span>
<span class="go">&#39;My string:Ee7vGi-ING6n02gkcJ-QLHg6vFw&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">signer</span><span class="o">.</span><span class="n">unsign</span><span class="p">(</span><span class="s1">&#39;My string:Ee7vGi-ING6n02gkcJ-QLHg6vFw&#39;</span><span class="p">)</span>
<span class="go">&#39;My string&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">signer</span><span class="o">.</span><span class="n">sign_object</span><span class="p">({</span><span class="s1">&#39;message&#39;</span><span class="p">:</span> <span class="s1">&#39;Hello!&#39;</span><span class="p">})</span>
<span class="go">&#39;eyJtZXNzYWdlIjoiSGVsbG8hIn0:-UWSLCE-oUAHzhkHviYz3SOZYBjFKllEOyVZNuUtM-I&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">signer</span><span class="o">.</span><span class="n">unsign_object</span><span class="p">(</span><span class="s1">&#39;eyJtZXNzYWdlIjoiSGVsbG8hIn0:-UWSLCE-oUAHzhkHviYz3SOZYBjFKllEOyVZNuUtM-I&#39;</span><span class="p">)</span>
<span class="go">{&#39;message&#39;: &#39;Hello!&#39;}</span>
</pre></div>
</div>
<p>以这种方式使用盐，会将不同的签名放入不同的命名空间。 来自一个命名空间的签名（一个特定的盐值）不能用于验证在使用不同盐值设置的不同命名空间中的同一明文字符串。这样做的结果是防止攻击者将代码中某个地方生成的签名字符串作为输入，输入到使用不同盐值生成（和验证）签名的另一段代码中。</p>
<p>与你的 <a class="reference internal" href="../ref/settings.html#std:setting-SECRET_KEY"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECRET_KEY</span></code></a> 不同，你的盐参数不需要保密。</p>
<div class="versionchanged">
<span class="title">Changed in Django 3.2:</span> <p>The <code class="docutils literal notranslate"><span class="pre">sign_object()</span></code> and <code class="docutils literal notranslate"><span class="pre">unsign_object()</span></code> methods were added.</p>
</div>
</div>
<div class="section" id="s-verifying-timestamped-values">
<span id="verifying-timestamped-values"></span><h3>验证时间戳值<a class="headerlink" href="#verifying-timestamped-values" title="永久链接至标题">¶</a></h3>
<p><code class="docutils literal notranslate"><span class="pre">TimestampSigner</span></code> 是 <a class="reference internal" href="#django.core.signing.Signer" title="django.core.signing.Signer"><code class="xref py py-class docutils literal notranslate"><span class="pre">Signer</span></code></a> 的子类，它给值附加一个签名的时间戳。这允许你确认一个签名的值是在特定时间内创建的：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">datetime</span> <span class="kn">import</span> <span class="n">timedelta</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.core.signing</span> <span class="kn">import</span> <span class="n">TimestampSigner</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">signer</span> <span class="o">=</span> <span class="n">TimestampSigner</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">value</span> <span class="o">=</span> <span class="n">signer</span><span class="o">.</span><span class="n">sign</span><span class="p">(</span><span class="s1">&#39;hello&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">value</span>
<span class="go">&#39;hello:1NMg5H:oPVuCqlJWmChm1rA2lyTUtelC-c&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">signer</span><span class="o">.</span><span class="n">unsign</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>
<span class="go">&#39;hello&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">signer</span><span class="o">.</span><span class="n">unsign</span><span class="p">(</span><span class="n">value</span><span class="p">,</span> <span class="n">max_age</span><span class="o">=</span><span class="mi">10</span><span class="p">)</span>
<span class="gp">...</span>
<span class="go">SignatureExpired: Signature age 15.5289158821 &gt; 10 seconds</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">signer</span><span class="o">.</span><span class="n">unsign</span><span class="p">(</span><span class="n">value</span><span class="p">,</span> <span class="n">max_age</span><span class="o">=</span><span class="mi">20</span><span class="p">)</span>
<span class="go">&#39;hello&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">signer</span><span class="o">.</span><span class="n">unsign</span><span class="p">(</span><span class="n">value</span><span class="p">,</span> <span class="n">max_age</span><span class="o">=</span><span class="n">timedelta</span><span class="p">(</span><span class="n">seconds</span><span class="o">=</span><span class="mi">20</span><span class="p">))</span>
<span class="go">&#39;hello&#39;</span>
</pre></div>
</div>
<dl class="class">
<dt id="django.core.signing.TimestampSigner">
<em class="property">class </em><code class="descname">TimestampSigner</code>(<em>key=None</em>, <em>sep=':'</em>, <em>salt=None</em>, <em>algorithm='sha256'</em>)<a class="headerlink" href="#django.core.signing.TimestampSigner" title="永久链接至目标">¶</a></dt>
<dd><dl class="method">
<dt id="django.core.signing.TimestampSigner.sign">
<code class="descname">sign</code>(<em>value</em>)<a class="headerlink" href="#django.core.signing.TimestampSigner.sign" title="永久链接至目标">¶</a></dt>
<dd><p>签名 <code class="docutils literal notranslate"><span class="pre">value</span></code> 并附加当前时间戳。</p>
</dd></dl>

<dl class="method">
<dt id="django.core.signing.TimestampSigner.unsign">
<code class="descname">unsign</code>(<em>value</em>, <em>max_age=None</em>)<a class="headerlink" href="#django.core.signing.TimestampSigner.unsign" title="永久链接至目标">¶</a></dt>
<dd><p>检查 <code class="docutils literal notranslate"><span class="pre">value</span></code> 是否在 <code class="docutils literal notranslate"><span class="pre">max_age</span></code> 秒前被签署，否则引发 <code class="docutils literal notranslate"><span class="pre">SignatureExpired</span></code>。<code class="docutils literal notranslate"><span class="pre">max_age</span></code> 参数可以接受一个整数或一个 <a class="reference external" href="https://docs.python.org/3/library/datetime.html#datetime.timedelta" title="(在 Python v3.10)"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime.timedelta</span></code></a> 对象。</p>
</dd></dl>

<dl class="method">
<dt id="django.core.signing.TimestampSigner.sign_object">
<code class="descname">sign_object</code>(<em>obj</em>, <em>serializer=JSONSerializer</em>, <em>compress=False</em>)<a class="headerlink" href="#django.core.signing.TimestampSigner.sign_object" title="永久链接至目标">¶</a></dt>
<dd><div class="versionadded">
<span class="title">New in Django 3.2.</span> </div>
<p>Encode, optionally compress, append current timestamp, and sign complex
data structure (e.g. list, tuple, or dictionary).</p>
</dd></dl>

<dl class="method">
<dt id="django.core.signing.TimestampSigner.unsign_object">
<code class="descname">unsign_object</code>(<em>signed_obj</em>, <em>serializer=JSONSerializer</em>, <em>max_age=None</em>)<a class="headerlink" href="#django.core.signing.TimestampSigner.unsign_object" title="永久链接至目标">¶</a></dt>
<dd><div class="versionadded">
<span class="title">New in Django 3.2.</span> </div>
<p>Checks if <code class="docutils literal notranslate"><span class="pre">signed_obj</span></code> was signed less than <code class="docutils literal notranslate"><span class="pre">max_age</span></code> seconds ago,
otherwise raises <code class="docutils literal notranslate"><span class="pre">SignatureExpired</span></code>. The <code class="docutils literal notranslate"><span class="pre">max_age</span></code> parameter can
accept an integer or a <a class="reference external" href="https://docs.python.org/3/library/datetime.html#datetime.timedelta" title="(在 Python v3.10)"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime.timedelta</span></code></a> object.</p>
</dd></dl>

<div class="versionchanged">
<span class="title">Changed in Django 3.1:</span> <p>加入 <code class="docutils literal notranslate"><span class="pre">algorithm</span></code> 参数。</p>
</div>
</dd></dl>

</div>
<div class="section" id="s-protecting-complex-data-structures">
<span id="s-signing-complex-data"></span><span id="protecting-complex-data-structures"></span><span id="signing-complex-data"></span><h3>保护复杂的数据结构<a class="headerlink" href="#protecting-complex-data-structures" title="永久链接至标题">¶</a></h3>
<p>If you wish to protect a list, tuple or dictionary you can do so using the
<code class="docutils literal notranslate"><span class="pre">Signer.sign_object()</span></code> and <code class="docutils literal notranslate"><span class="pre">unsign_object()</span></code> methods, or signing module's
<code class="docutils literal notranslate"><span class="pre">dumps()</span></code> or <code class="docutils literal notranslate"><span class="pre">loads()</span></code> functions (which are shortcuts for
<code class="docutils literal notranslate"><span class="pre">TimestampSigner(salt='django.core.signing').sign_object()/unsign_object()</span></code>).
These use JSON serialization under the hood. JSON ensures that even if your
<a class="reference internal" href="../ref/settings.html#std:setting-SECRET_KEY"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECRET_KEY</span></code></a> is stolen an attacker will not be able to execute
arbitrary commands by exploiting the pickle format:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.core</span> <span class="kn">import</span> <span class="n">signing</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">signer</span> <span class="o">=</span> <span class="n">signing</span><span class="o">.</span><span class="n">TimestampSigner</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">value</span> <span class="o">=</span> <span class="n">signer</span><span class="o">.</span><span class="n">sign_object</span><span class="p">({</span><span class="s1">&#39;foo&#39;</span><span class="p">:</span> <span class="s1">&#39;bar&#39;</span><span class="p">})</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">value</span>
<span class="go">&#39;eyJmb28iOiJiYXIifQ:1kx6R3:D4qGKiptAqo5QW9iv4eNLc6xl4RwiFfes6oOcYhkYnc&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">signer</span><span class="o">.</span><span class="n">unsign_object</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>
<span class="go">{&#39;foo&#39;: &#39;bar&#39;}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">value</span> <span class="o">=</span> <span class="n">signing</span><span class="o">.</span><span class="n">dumps</span><span class="p">({</span><span class="s1">&#39;foo&#39;</span><span class="p">:</span> <span class="s1">&#39;bar&#39;</span><span class="p">})</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">value</span>
<span class="go">&#39;eyJmb28iOiJiYXIifQ:1kx6Rf:LBB39RQmME-SRvilheUe5EmPYRbuDBgQp2tCAi7KGLk&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">signing</span><span class="o">.</span><span class="n">loads</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>
<span class="go">{&#39;foo&#39;: &#39;bar&#39;}</span>
</pre></div>
</div>
<p>由于 JSON 的特性（列表和元组之间没有原生的区别），如果你传入一个元组，你将从 <code class="docutils literal notranslate"><span class="pre">signing.loads(object)</span></code> 得到一个列表：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.core</span> <span class="kn">import</span> <span class="n">signing</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">value</span> <span class="o">=</span> <span class="n">signing</span><span class="o">.</span><span class="n">dumps</span><span class="p">((</span><span class="s1">&#39;a&#39;</span><span class="p">,</span><span class="s1">&#39;b&#39;</span><span class="p">,</span><span class="s1">&#39;c&#39;</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">signing</span><span class="o">.</span><span class="n">loads</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>
<span class="go">[&#39;a&#39;, &#39;b&#39;, &#39;c&#39;]</span>
</pre></div>
</div>
<dl class="function">
<dt id="django.core.signing.dumps">
<code class="descname">dumps</code>(<em>obj</em>, <em>key=None</em>, <em>salt='django.core.signing'</em>, <em>serializer=JSONSerializer</em>, <em>compress=False</em>)<a class="headerlink" href="#django.core.signing.dumps" title="永久链接至目标">¶</a></dt>
<dd><p>返回 URL 安全的，经过签名的 base64 压缩 JSON 字符串。使用 <a class="reference internal" href="#django.core.signing.TimestampSigner" title="django.core.signing.TimestampSigner"><code class="xref py py-class docutils literal notranslate"><span class="pre">TimestampSigner</span></code></a> 对序列化对象进行签名。</p>
</dd></dl>

<dl class="function">
<dt id="django.core.signing.loads">
<code class="descname">loads</code>(<em>string</em>, <em>key=None</em>, <em>salt='django.core.signing'</em>, <em>serializer=JSONSerializer</em>, <em>max_age=None</em>)<a class="headerlink" href="#django.core.signing.loads" title="永久链接至目标">¶</a></dt>
<dd><p>与 <code class="docutils literal notranslate"><span class="pre">dumps()</span></code> 相反，如果签名失败引发 <code class="docutils literal notranslate"><span class="pre">BadSignature</span></code>。如果给定，则检查 <code class="docutils literal notranslate"><span class="pre">max_age</span></code> （以秒为单位）。</p>
</dd></dl>

<div class="versionchanged">
<span class="title">Changed in Django 3.2:</span> <p>The <code class="docutils literal notranslate"><span class="pre">sign_object()</span></code> and <code class="docutils literal notranslate"><span class="pre">unsign_object()</span></code> methods were added.</p>
</div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">加密签名</a><ul>
<li><a class="reference internal" href="#protecting-the-secret-key">保护 <code class="docutils literal notranslate"><span class="pre">SECRET_KEY</span></code></a></li>
<li><a class="reference internal" href="#using-the-low-level-api">使用低级 API</a><ul>
<li><a class="reference internal" href="#using-the-salt-argument">使用 <code class="docutils literal notranslate"><span class="pre">salt</span></code> 参数</a></li>
<li><a class="reference internal" href="#verifying-timestamped-values">验证时间戳值</a></li>
<li><a class="reference internal" href="#protecting-complex-data-structures">保护复杂的数据结构</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>上一个主题</h4>
  <p class="topless"><a href="conditional-view-processing.html"
                        title="上一章">条件视图处理</a></p>
  <h4>下一个主题</h4>
  <p class="topless"><a href="email.html"
                        title="下一章">发送邮件</a></p>
  <div role="note" aria-label="source link">
    <h3>本页</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/topics/signing.txt"
            rel="nofollow">显示源代码</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>快速搜索</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="转向" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">12月 07, 2021</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="conditional-view-processing.html" title="条件视图处理">previous</a>
     |
    <a href="index.html" title="使用 Django" accesskey="U">up</a>
   |
    <a href="email.html" title="发送邮件">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>